package reverseKGroup

type ListNode struct {
	Val  int
	Next *ListNode
}

func ReverseKGroup(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	tail := head
	for i := 0; i < k; i++ {
		if tail == nil {
			return head
		}
		tail = tail.Next
	}

	newHead := reverse(head, tail)
	head.Next = ReverseKGroup(tail, k)
	return newHead
}

func reverse(head *ListNode, tail *ListNode) *ListNode {

	pre := &ListNode{}
	next := &ListNode{}
	for head != tail {
		next = head.Next
		head.Next = pre
		pre = head
		head = next

	}

	return pre

}
